package com.yayan.beautyclub.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yayan.beautyclub.bean.Product;
import com.yayan.beautyclub.service.CategoryService;
import com.yayan.beautyclub.service.IProductService;
import com.yayan.util.EncodingUtil;
import com.yayan.util.UploadUtil;

@Controller
@RequestMapping(value="/product", method=RequestMethod.POST)
public class ProductController {

	@Autowired
	private IProductService productService;
	
	private String rootUrl = null;
	private String titlePic = null;
	private String decPic = null;
	private String editTitlePic = null;
	private String editDecPic = null;
	
	/**
	 * 上传图片检查
	 * @param pic
	 * @param request
	 * @param response
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value="/uploadPic.do")
	@ResponseBody
	public void uploadCheck(MultipartFile pic, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException {
		JSONObject jsonObject = new JSONObject();
		if(pic != null){
			if(pic.getSize() >= 5242880){
				jsonObject.put("status", false);
				jsonObject.put("msg", "图片大小不能超过5M");
			}else if(UploadUtil.checkExtention(pic)){
				String name = request.getParameter("name");
				// 获取图片原始文件名
				String originalFilename = pic.getOriginalFilename();
				// 文件名使用当前时间
				String currentName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());				
				String url = request.getSession().getServletContext().getRealPath("") + "upload/";
				//System.out.println(url);
				rootUrl = url;
				File dir = new File(url);
				if(!dir.exists()) {
					dir.mkdirs();
				}
				if(name.equals("titlePic")){
					if(titlePic != null && !titlePic.isEmpty()){
						dir = new File(url+titlePic);
						if(dir.isFile() && dir.exists())
							dir.delete();
					}
					currentName += "_titlePic_." + FilenameUtils.getExtension(originalFilename);
					titlePic = currentName;
				}else if(name.equals("decPic")){
					if(decPic != null && !decPic.isEmpty()){
						dir = new File(url+decPic);
						if(dir.isFile() && dir.exists())
							dir.delete();
					}
					currentName += "_decPic_." + FilenameUtils.getExtension(originalFilename);
					decPic = currentName;
				}
				// 上传图片
				pic.transferTo(new File(url+currentName));				
				jsonObject.put("status", true);
			}else{
				//图片格式不正确，返回提示信息
				jsonObject.put("status", false);
				jsonObject.put("msg", "上传图片格式必须是jpg/png/jpeg");
			}
		}else{
			jsonObject.put("status", false);
			jsonObject.put("msg", "上传失败！服务器未能接收图片！");
		}
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().write(jsonObject.toString());
	}
	
	/**
	 * 后台管理产品录入
	 * @param product
	 * @return
	 */
	@RequestMapping(value="/create.do",produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String createProduct(Product product){			
		if(product.getParent() == 0)
			return "请选择产品所属一级分类";
		if(product.getcId() == 0)
			return "请选择产品类别！";
		
		if(titlePic == null || decPic == null || titlePic.equals("") || decPic.equals("")){
			return "提交失败，图片未能上传！";
		}
		product.setTitlePic(titlePic);
		product.setImages(decPic);	
		if(productService.saveProduct(product) == 0)
			return "提交失败，请检查输入信息是否正确！";
		titlePic = null;
		decPic = null;
		return "true";
	}
	
	/**
	 * 后台管理，编辑产品信息
	 * @param product
	 * @return
	 */
	@RequestMapping(value="/edit.do",produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String editProduct(Product product){
		if(product.getParent() == 0)
			return "请选择产品所属一级分类";
		if(product.getcId() == 0)
			return "请选择产品类别！";
		if(titlePic != null && !titlePic.isEmpty()){
			deleteFile(rootUrl+editTitlePic);
			editTitlePic = titlePic;			
			titlePic = null;			
		}
		if(decPic != null && !decPic.isEmpty()){
			deleteFile(rootUrl+editDecPic);
			editDecPic = decPic;			
			decPic = null;			
		}
		product.setTitlePic(editTitlePic);
		product.setImages(editDecPic);	
		if(!productService.updateProduct(product))
			return "提交失败，请检查输入信息是否正确！";		
		return "true";
	}
	
	/**
	 * 后台管理分页获取产品列表
	 * @param page
	 * @param size
	 * @param first
	 * @param second
	 * @param search
	 * @return
	 */
	@RequestMapping(value="/product.do")
	@ResponseBody
	public List<Map<String, Object>> reservePage(String page, String size, String first, String second, String search){
		search = EncodingUtil.encodeStr(search);		
		int intPage = Integer.parseInt(page);
		int intSize = Integer.parseInt(size);
		int intFirst = Integer.parseInt(first);
		int intSecond = Integer.parseInt(second);
		List<Map<String, Object>> list = productService.findProductByCondition(intPage, intSize, intFirst, intSecond, search);
		return list;
	}
	
	/**
	 * 后台管理删除产品
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/delete_product.do")
	@ResponseBody
	public boolean deleteProduct(@RequestBody Map<String, String> map){
		long pId = Long.parseLong(map.get("pId"));
		return productService.deleteProduct(pId);
	}
	
	/**
	 * 前台页面根据一级类别id分页获取产品信息列表
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/list_byparent.do")
	@ResponseBody
	public Map<String, Object> getProductListByParentId(@RequestBody Map<String, String> map){		
		int parentId = Integer.parseInt(map.get("parentId"));
		int page = Integer.parseInt(map.get("page"));
		int size = Integer.parseInt(map.get("size"));
		List<Product> list = null;
		if(parentId != 0 && page > 0 && size > 0){
			list = productService.findProductByParentId(parentId, page, size);
		}
		Map<String, Object> result = new HashMap<String, Object>();
		if(list == null || list.size() <= 1){
			result.put("size", 0);
			result.put("message", "没有找到满足条件的结果！");
		}else{
			result.put("size", list.remove(0).getStatus());
			result.put("list", list);
		}		
		return result;
	}
	
	/**
	 * 根据产品id获取产品详细信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/get_product.do")
	@ResponseBody
	public Map<String, Object> getProduct(@RequestBody Map<String, String> map){		
		long pId = Long.parseLong(map.get("pId"));
		return productService.findProductBypId(pId);
	}
	
	/**
	 * 根据产品id获取产品详细信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/get_editinfo.do")
	@ResponseBody
	public Map<String, Object> getProductAndCategory(@RequestBody Map<String, String> map){		
		long pId = Long.parseLong(map.get("pId"));
		Map<String, Object> result = productService.findProductBypId(pId);
		result.put("category", new CategoryService().getCategoryList(0));
		//判断是否有未删除的临时图片
		if(titlePic != null && !titlePic.isEmpty())
			deleteFile(rootUrl+titlePic);
		if(decPic != null && !decPic.isEmpty())
			deleteFile(rootUrl+decPic);
		editTitlePic = result.get("titlePic").toString();
		editDecPic = result.get("images").toString();
		titlePic = null;
		decPic = null;
		return result;
	}
	
	/**
	 * 前台页面根据二级分类id分页获取产品信息列表
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/list_bycid.do")
	@ResponseBody
	public Map<String, Object> getProductListByCId(@RequestBody Map<String, String> map){		
		int cId = Integer.parseInt(map.get("cId"));
		int page = Integer.parseInt(map.get("page"));
		int size = Integer.parseInt(map.get("size"));
		List<Product> list = null;
		if(cId != 0 && page >= 0 && size > 0){
			list = productService.findProductBycId(cId, page, size);
		}
		Map<String, Object> result = new HashMap<String, Object>();
		if(list == null || list.size() <= 1){
			result.put("size", 0);
			result.put("message", "没有找到满足条件的结果！");
		}else{
			result.put("size", list.remove(0).getStatus());
			result.put("list", list);
		}		
		return result;
	}
	
	/**
	 * 获取特价活动商品列表
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/product_list.do")
	@ResponseBody
	public List<Product> getProductList(){
		return productService.findProductByActivity();
	}
	
	/**
	 * 删除已存在图片
	 * @param url
	 */
	private void deleteFile(String url){
		File file = new File(url);
		if(file.isFile() && file.exists())
			file.delete();
	}
	
}
